package com.kitty.game.map.service;

import com.kitty.common.model.Pos;
import com.kitty.common.utils.SpringUtils;
import com.kitty.common.utils.ConcurrentHashSet;
import com.kitty.game.ServerService;
import com.kitty.game.config.GameMap;
import com.kitty.game.config.NPC;
import com.kitty.game.config.Transfer;
import com.kitty.game.enter.*;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.fight.service.BroadcastService;
import com.kitty.game.i18n.I18nId;
import com.kitty.game.map.MapDataPool;
import com.kitty.game.map.model.GroupMapParam;
import com.kitty.game.npc.NpcDataPool;
import com.kitty.game.npc.service.appreace.AppearanceHandler;
import com.kitty.game.pk.service.PkService;
import com.kitty.game.role.message.RespAppear;
import com.kitty.game.role.model.Role;
import com.kitty.game.role.service.RoleService;
import com.kitty.game.scene.SceneManager;
import com.kitty.game.team.message.RespMsg;
import com.kitty.game.utils.Const;
import com.kitty.game.zhounian.kuozhan.Resexelua;
import com.kitty.listener.BaseGameEvent;
import com.kitty.listener.EventDispatcher;
import com.kitty.listener.EventType;
import com.kitty.listener.annotation.EventHandler;
import com.kitty.listener.event.EnterMapEvent;
import com.kitty.listener.event.LeaveMapEvent;
import com.kitty.listener.event.MoveEvent;
import com.kitty.mina.cache.DataCache;
import com.kitty.mina.cache.SessionCache;
import com.kitty.mina.message.Message;
import com.kitty.mina.message.MessagePusher;
import org.nutz.dao.Dao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.text.MessageFormat;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;


@Service
public class MapService {

    private Logger logger = LoggerFactory.getLogger(MapService.class);
    @Autowired
    Dao dao;
    @Autowired
    ServerService serverService;
    @Autowired
    RoleService roleService;
    @Autowired
    BroadcastService broadcastService;

    private static final String NOT_CHANGE_MAP = "{0}不可以切换地图";

    /**
     * 进入地图
     */
    @EventHandler(EventType.ENTER_MAP)
//	public void handleEnterMapEvent(EnterMapEvent enterMapEvent) throws InterruptedException {
    public void handleEnterMapEvent(EnterMapEvent enterMapEvent) {
        Role role = enterMapEvent.getRole();
        int mapId = role.getPos().getMapId();
        /**所在地图不存在时，进行修复*/
        GameMap gameMap = getMap(mapId);
        if (gameMap == null) {
            role.setPos(new Pos());
            mapId = role.getPos().getMapId();
        }
        /**进入地图的时候发*/
        RespClearAllRole respClearAllRole = new RespClearAllRole();
        respClearAllRole.setRoleId(role.getRoleId());
        respClearAllRole.setMapId(mapId);
        MessagePusher.pushMessage(role, respClearAllRole);

        /**将角色ID加入地图缓存*/
        cache(role, mapId);

        /**进入地图*/
        sendEnterMap(role);
        /**发送传送点*/
        sendGameMapTransmission(role, mapId);

       // RespPlayInstruction playInstruction = new RespPlayInstruction();
        //playInstruction.setType((short)1000);
       // MessagePusher.pushMessage(role, playInstruction);

        /**发送npc*/
        try {
            broadcastNpc(role, mapId);
        } catch (Exception e) {
            logger.error("", e);
        }
        role.save();
        broadcastService.sendAppear(role);

        changeMapForEvent(role,enterMapEvent.getOldMapId(),mapId);
        //Resqietu resqietu = new Resqietu();
       // MessagePusher.pushMessage(role, resqietu);



       SceneManager.INSTANCE.enterMap(mapId, role);



        //ResWHOPEN resWHOPEN = new ResWHOPEN();
       // MessagePusher.pushMessage(role, resWHOPEN);
//logger.error("我跑到这里了？？？？？？？？？？？？？？？？？？？？");
    }

    /**
     * 移动事件
     */
    @EventHandler(EventType.MOVE)
    public void handleLoginEvent(MoveEvent moveEvent) {
        Role role = moveEvent.getRole();
        SceneManager.INSTANCE.movePosition(role);
    }

    /**
     * 离开地图事件
     */
    @EventHandler(EventType.LEAVE_MAP)
    public void handleLeaveMapEvent(LeaveMapEvent leaveMapEvent) {
        Role role = leaveMapEvent.getRole();
        int oldMapId = leaveMapEvent.getMapId();
        /**删除缓存的信息*/
        removeCache(role, oldMapId);
        SceneManager.INSTANCE.leaveMap(oldMapId, role);
        List<NPC> list = getNpcList(new GroupMapParam(role), oldMapId);
        // 清空上一个地图的npc
        if (list != null) {
            for (NPC npc : list) {//给发送NPC消失包
                RespDisappear respDisappear = new RespDisappear();
                respDisappear.setId(npc.getId());
                respDisappear.setType((short) Const.NPC);
                MessagePusher.pushMessage(role, respDisappear);
            }
        }
    }
    //地图变更，不同类型的话 修改宠物参战a
    public void changeMapForEvent(Role role,int oldMapId,int nowMapId){
        MapService mapService = SpringUtils.getBean(MapService.class);
        int i = mapService.queryMapIdType(oldMapId);
        int k = mapService.queryMapIdType(nowMapId);
        if(mapService.queryMapIdType(nowMapId) == 2){
            role.getPetBox().setSupplyPetId(role.getPetBox().getSupplyGhostPetId());
            role.getPetBox().setFightPetId(role.getPetBox().getFightGhostPetId());
        }else{
            role.getPetBox().setSupplyPetId(role.getPetBox().getSupplyYangPetId());
            role.getPetBox().setFightPetId(role.getPetBox().getFightYangPetId());
        }
        //更换阴间阳间地图
        if(i != k){
            roleService.sendExtraAttribute(role);
        }
    }

    /**
     * 初始化地图信息
     */
    public void initMapInfo(List<GameMap> maps) {
        Map<Integer, GameMap> id2GameMaps = new HashMap<>(maps.size());
        Map<String, Integer> mapName2Id = new HashMap<>(maps.size());
        for (GameMap gameMap : maps) {
            id2GameMaps.put(gameMap.getId(), gameMap);
            mapName2Id.put(gameMap.getName(), gameMap.getId());

        }
        MapDataPool.id2GameMaps = id2GameMaps;
        MapDataPool.mapName2Id = mapName2Id;
    }


    /**
     * 传送点初始化
     */
    public void initTrasfer(List<Transfer> list) {
        Map<Integer, HashSet<Short>> mapId2Trasfer = new HashMap<>();
        Map<Short, Transfer> trasferId2Trasfer = new HashMap<>(list.size());
        for (Transfer transfer : list) {
            trasferId2Trasfer.put(transfer.getId(), transfer);

            Set<Short> idSet = mapId2Trasfer.computeIfAbsent(transfer.getFromMapId(), k -> new HashSet<>());
            idSet.add(transfer.getId());

        }

        MapDataPool.mapId2TrasferIdSet = mapId2Trasfer;
        MapDataPool.trasferId2Trasfer = trasferId2Trasfer;
    }

    /**
     * 地图名称取地图ID
     */
    public int getMapIdByName(String mapName) {
        return MapDataPool.mapName2Id.get(mapName);
    }

    public List<NPC> getNpcList(GroupMapParam groupMapParam, int mapId) {
        Set<Integer> set = DataCache.MAP_NPCIDS.get(mapId);
        ArrayList<NPC> arrayList = new ArrayList<>();
        if (set != null) {
            for (Integer npcId : set) {
                NPC npc = DataCache.ID_NPC.get(npcId);
                if (npc == null) {
                    continue;
                }
                arrayList.add(npc);
            }
        }
        // 如果是试道内
        if (mapId == Const.SHIDAO_MAPID){
            Function<Role, Serializable> mapKeyGenerater = MapDataPool.MAP_KEY_GENERATERS.get(mapId);
            if (mapKeyGenerater != null) {
                Map<Serializable, Set<Integer>> map = DataCache.GROUP_MAP_NPCIDS.get(mapId);
                if (map != null) {
                    Serializable key = groupMapParam.getRole() != null ? mapKeyGenerater.apply(groupMapParam.getRole())
                            : groupMapParam.getGroupKey();
                    set = key != null ? map.get(key) : null;
                    if (set != null) {
                        for (Integer npcId : set) {
                            NPC npc = DataCache.GROUP_NPC.get(npcId);
                            if (npc == null) {
                                continue;
                            }
                            arrayList.add(npc);
                        }
                        return arrayList;
                    }
                }
            }
        }

        set = DataCache.TASK_MAP_NPC.get(mapId);
        if (set != null) {
            for (Integer npcId : set) {
                NPC npc = DataCache.TASK_NPCS.get(npcId);
                if (npc == null) {
                    continue;
                }
                arrayList.add(npc);
            }
        }

        set = DataCache.PIRATE_MAP_NPC.get(mapId);
        if (set != null) {
            for (Integer npcId : set) {
                NPC npc = DataCache.PIRATE_NPCS.get(npcId);
                NPC npc1 = DataCache.DIFUPANNI_NPCS.get(npcId);
                NPC npc2 = DataCache.YIZUXIAOJIANG_NPCS.get(npcId);
                NPC npc3 = DataCache.TIANJIEPANNI_NPCS.get(npcId);
                NPC npc4 = DataCache.YUANHUN_NPCS.get(npcId);
                NPC npc5 = DataCache.MONSTER_NPCS.get(npcId);
                NPC npc6 = DataCache.CAISHEN_NPCS.get(npcId);
                NPC npc7 = DataCache.FUXING_NPCS.get(npcId);
                if (npc == null && npc1 == null && npc2 == null && npc3  == null && npc4 == null&& npc5 == null&& npc6 == null&& npc7 == null) {
                    continue;
                }
                if(npc != null){
                    arrayList.add(npc);
                }else if(npc1 != null){
                    arrayList.add(npc1);
                }else if(npc2 != null){
                    arrayList.add(npc2);
                }else if(npc3 != null){
                    arrayList.add(npc3);
                }else if(npc4 != null){
                    arrayList.add(npc4);
                }else if(npc5 != null){
                    arrayList.add(npc5);
                }else if(npc6 != null){
                    arrayList.add(npc6);
                }else if(npc7 != null){
                    arrayList.add(npc7);
                }

            }
        }
        set = DataCache.XING_MAP_NPC.get(mapId);
        if (set != null) {
            for (Integer npcId : set) {
                NPC npc = DataCache.XING_NPCS.get(npcId);
                if (npc == null) {
                    continue;
                }
                arrayList.add(npc);
            }
        }
        set = DataCache.SHIDAO_LIST.get(mapId);
        if (set != null) {
            for (Integer npcId : set) {
                NPC npc = DataCache.SHIDAO_NPC.get(npcId);
                if (npc == null) {
                    continue;
                }
                arrayList.add(npc);
            }
        }


        set = DataCache.MONSTER_MAP_NPC.get(mapId);
        if (set != null) {
            for (Integer npcId : set) {
                NPC npc = DataCache.MONSTER_NPCS.get(npcId);
                if (npc == null) {
                    continue;
                }
                arrayList.add(npc);
            }
        }
        set = DataCache.TIANBING_MAP_NPC.get(mapId);
        if (set != null) {
            for (Integer npcId : set) {
                NPC npc = DataCache.TIANBING_NPCS.get(npcId);
                if (npc == null) {
                    continue;
                }
                arrayList.add(npc);
            }
        }
        set = DataCache.CAISHEN_MAP_NPC.get(mapId);
        if (set != null) {
            for (Integer npcId : set) {
                NPC npc = DataCache.CAISHEN_NPCS.get(npcId);
                if (npc == null) {
                    continue;
                }
                arrayList.add(npc);
            }
        }
        set = DataCache.FUXING_MAP_NPC.get(mapId);
        if (set != null) {
            for (Integer npcId : set) {
                NPC npc = DataCache.FUXING_NPCS.get(npcId);
                if (npc == null) {
                    continue;
                }
                arrayList.add(npc);
            }
        }
        // 上古妖王
        set = DataCache.SHANGGU_LIST.get(mapId);
        if (set != null) {
            for (Integer npcId : set) {
                NPC npc = DataCache.SHANGGU_NPC.get(npcId);
                if (npc == null) {
                    continue;
                }
                arrayList.add(npc);
            }
        }
        {
            Function<Role, Serializable> mapKeyGenerater = MapDataPool.MAP_KEY_GENERATERS.get(mapId);
            if (mapKeyGenerater != null) {
                Map<Serializable, Set<Integer>> map = DataCache.GROUP_MAP_NPCIDS.get(mapId);
                if (map != null) {
                    Serializable key = groupMapParam.getRole() != null ? mapKeyGenerater.apply(groupMapParam.getRole())
                            : groupMapParam.getGroupKey();
                    set = key != null ? map.get(key) : null;
                    if (set != null) {
                        for (Integer npcId : set) {
                            NPC npc = DataCache.GROUP_NPC.get(npcId);
                            if (npc == null) {
                                continue;
                            }
                            arrayList.add(npc);
                        }
                    }
                }
            }
        }


        return arrayList;
    }

    public NPC getNpc(int id) {
        NPC npc = DataCache.ID_NPC.get(id);
        if (npc != null) {
            return npc;
        }
        npc = NpcDataPool.taskNpcMap.get(id);
        if (npc != null) {
            return npc;
        }
        npc = DataCache.TASK_NPCS.get(id);
        if (npc != null) {
            return npc;
        }
        npc = DataCache.PIRATE_NPCS.get(id);
        if (npc != null) {
            return npc;
        }
        npc = DataCache.DIFUPANNI_NPCS.get(id);
        if (npc != null) {
            return npc;
        }
        npc = DataCache.YIZUXIAOJIANG_NPCS.get(id);
        if (npc != null) {
            return npc;
        }
        npc = DataCache.TIANJIEPANNI_NPCS.get(id);
        if (npc != null) {
            return npc;
        }
        npc = DataCache.YUANHUN_NPCS.get(id);
        if (npc != null) {
            return npc;
        }
        npc = DataCache.XING_NPCS.get(id);
        if (npc != null) {
            return npc;
        }
        npc = DataCache.SHIDAO_NPC.get(id);
        if (npc != null) {
            return npc;
        }
        npc = DataCache.SHANGGU_NPC.get(id);
        if (npc != null) {
            return npc;
        }
        npc = DataCache.GROUP_NPC.get(id);
        if (npc != null) {
            return npc;
        }
        npc = DataCache.BOSS_NPC.get(id);
        if (npc != null) {
            return npc;
        }
        npc = DataCache.MONSTER_NPCS.get(id);
        if (npc != null) {
            return npc;
        }
        npc = DataCache.CAISHEN_NPCS.get(id);
        if (npc != null) {
            return npc;
        }
        npc = DataCache.FUXING_NPCS.get(id);
        if (npc != null) {
            return npc;
        }

        return npc;
    }

    public NPC getNpcByName(String name) {
        Integer npcId = DataCache.NAME_NPCID.get(name);
        if (npcId == null) {
            return null;
        }

        return getNpc(npcId);
    }

    public List<MapTransmission> getTrasferInfo(int mapId) {

        Set<Short> set = MapDataPool.mapId2TrasferIdSet.get(mapId);//jedisService.smembers(Const.trasfer + mapId);
        if (set == null || set.size() <= 0) {
            return new ArrayList<>();
        }
        List<MapTransmission> list = new ArrayList<>();
        for (Short transferId : set) {
            Transfer transfer = getTransferById(transferId);
            MapTransmission MapTransmission = new MapTransmission();
            MapTransmission.setName(transfer.getToMap());
            MapTransmission.setX(transfer.getFromX());
            MapTransmission.setY(transfer.getFromY());
            MapTransmission.setDir((short) 8);
            list.add(MapTransmission);
        }
        return list;

    }

    /**
     * 根据目标地图名和当前取传送点
     */
    public Transfer getTrasfer(String toMap, int fromMapId) {
        Set<Short> set = MapDataPool.mapId2TrasferIdSet.get(fromMapId);
        for (Short transferId : set) {
            Transfer transfer = getTransferById(transferId);
            if (transfer.getToMap().equals(toMap)) {
                return transfer;
            }
        }
        return null;

    }

    /**
     * 地图ID取地图信息
     */
    public GameMap getMap(int mapId) {
        return MapDataPool.id2GameMaps.get(mapId);

    }

    /**
     * mapId 取当前地图的角色ID集合
     */
    public ConcurrentHashSet<Integer> getRoleIds(GroupMapParam groupMapParam, int mapId) {
        Function<Role, Serializable> mapKeyGenerater = MapDataPool.MAP_KEY_GENERATERS.get(mapId);
        if (mapKeyGenerater != null) {
            Map<Serializable, ConcurrentHashSet<Integer>> map = SessionCache.GROUP_MAPID_ROLEIDS.get(mapId);
            if (map == null) {
                return null;
            }

            Serializable key = groupMapParam.getRole() != null ? mapKeyGenerater.apply(groupMapParam.getRole())
                    : groupMapParam.getGroupKey();
            if (key == null) {
                return null;
            }
            return map.get(key);
        }

        return SessionCache.MAPID_ROLEIDS.get(mapId);
    }

    /**
     * 通过传送点ID取传送点信息
     */
    public Transfer getTransferById(short transferId) {
        return MapDataPool.trasferId2Trasfer.get(transferId);
    }

    public void cache(Role role, int mapId) {
        // 缓存当前登录角色地图ID信息
        ConcurrentHashSet<Integer> set = null;
        Function<Role, Serializable> mapKeyGenerater = MapDataPool.MAP_KEY_GENERATERS.get(mapId);
        if (mapKeyGenerater != null) {
            Serializable key = mapKeyGenerater.apply(role);
            if (key == null) {
                return;
            }

            Map<Serializable, ConcurrentHashSet<Integer>> map = SessionCache.GROUP_MAPID_ROLEIDS.get(mapId);
            if (map == null) {
                map = SessionCache.GROUP_MAPID_ROLEIDS.putIfAbsent(mapId, new ConcurrentHashMap<>());
                if (map == null) {
                    map = SessionCache.GROUP_MAPID_ROLEIDS.get(mapId);
                }
            }
            set = map.get(key);
            if (set == null) {
                set = map.putIfAbsent(key, new ConcurrentHashSet<>());
                if (set == null) {
                    set = map.get(key);
                }
            }
        } else {
            set = SessionCache.MAPID_ROLEIDS.get(mapId);
            if (set == null) {
                set = SessionCache.MAPID_ROLEIDS.put(mapId, new ConcurrentHashSet<>());
                if (set == null) {
                    set = SessionCache.MAPID_ROLEIDS.get(mapId);
                }
            }
        }

        set.add(role.getRoleId());
    }


    private void removeCache(Role role, int oldMapId) {
        // 删除原来地图存储的roleId
        ConcurrentHashSet<Integer> set = null;
        Function<Role, Serializable> mapKeyGenerater = MapDataPool.MAP_KEY_GENERATERS.get(oldMapId);
        if (mapKeyGenerater != null) {
            Map<Serializable, ConcurrentHashSet<Integer>> map = SessionCache.GROUP_MAPID_ROLEIDS.get(oldMapId);
            if (map != null) {
                Serializable key = mapKeyGenerater.apply(role);
                set = key != null ? map.get(key) : null;
            }
        } else {
            set = SessionCache.MAPID_ROLEIDS.get(oldMapId);
        }

        if (set != null) {
            set.remove(role.getRoleId());
        }
    }

    /**
     * 更换地图
     */
    public void changeMap(Role role, int mapId, int x, int y) {
        if (role == null) {
            return;
        }
        if (serverService.getServer().getId() == 10000 ){
            if (mapId != Const.SHIDAO_MAPID && mapId != 38000){
                MessagePusher.pushMessage(role,new RespNotifyMiscEx("跨服试道中，不能切换地图。"));
                return;
            }
        }
        GameMap gameMap = getMap(mapId);
        if (gameMap == null) {
            return;
        }
        if (!checkChangeMap(role)) {
            return;
        }
//        /**已经目标地图，返回*/
//        if (role.getPos().getMapId() == mapId) {
//            return ;
//        }

        /**产生一个离开地图事件*/
        int oldMapId = role.getPos().getMapId();
        //如果是在监狱内，要刷新角色的形象，关闭飞行器
        if(oldMapId == 5015 || mapId ==5015){
            SceneManager.INSTANCE.sendMessages(role, new Message[]{SpringUtils.getBean(BroadcastService.class).getUpdateAppear(role)});
        }
        EventDispatcher.getInstance().fireEvent(new LeaveMapEvent(EventType.LEAVE_MAP, role, oldMapId));

        role.setPos(x, y, 5, mapId);
        /**产生一个进入地图事件*/
        EventDispatcher.getInstance().fireEvent(new EnterMapEvent(EventType.ENTER_MAP, role,oldMapId));
    }


    /**
     * 更换地图
     *
     * @param role
     * @param reqTelePort
     */
    public void changeMap(Role role, ReqTelePort reqTelePort) {

        changeMap(role, reqTelePort.getMapId(), reqTelePort.getX(), reqTelePort.getY());
        long now = System.currentTimeMillis();
        role.setPrevMoveTime(now+300);
        RespPositionMove respPositionMove = new RespPositionMove();
        respPositionMove.setRoleId(role.getRoleId());
        respPositionMove.setX((short)reqTelePort.getX());
        respPositionMove.setY((short)reqTelePort.getY());
        respPositionMove.setDir(role.getPos().getDir());
        MessagePusher.pushMessage(role, respPositionMove);
    }

    /**
     * 切换地图检测
     */
    private boolean checkChangeMap(Role role) {
        /**需要检测，同时在限制地图时，提示信息并返回false*/
        if (role.popTempCache(Const.NOT_CHECK_CHANGE_MAP) == null
                && MapDataPool.NOT_CHANGE_MAPS.contains(role.getPos().getMapId())) {
            GameMap gameMap = getMap(role.getPos().getMapId());
            String msg = MessageFormat.format(NOT_CHANGE_MAP, gameMap.getName());
            SpringUtils.getTeamService().pushMessage(role, new RespMsg(msg));
            return false;
        }

        /**在监狱不能切换地图*/
        if (SpringUtils.getBean(PkService.class).isInPrisonTime(role)) {
            MessagePusher.notify2Player(role, I18nId.PMT_1113);
            return false;
        }

        return true;
    }


    /**
     * 进入地图包
     */
    public void sendEnterMap(Role role) {
        sendEnterMap(role, role.getPos());
    }

    public void sendEnterMap(Role role, Pos pos) {
        GameMap gameMap = getMap(pos.getMapId());
       // RespEnterMap resEnterMap = new RespEnterMap();
        Resexelua resexelua = new Resexelua();

// CharMgr:setVisible(true) Me:setChangeRoom(true) ldata.is_task_walk=false

        String map_s = "" ; //"local ldata = {} ldata.map_id = "+ pos.getMapId() +" ldata.x = "+pos.getX()+ " ldata.y = "+pos.getY()+" ldata.dir = "+pos.getY()+"   ldata.enter_effect_index = 0 ldata.enter_effect_index = 0  ldata.compact_map_index = 0 ldata.map_name = [["+gameMap.getName()+"]] MapMgr:MSG_ENTER_ROOM(ldata, true)";//true
        map_s = "local ldata = {} ldata.map_id =" + pos.getMapId()  + "  ldata.x = " + pos.getX() + " ldata.y = " + pos.getY() + " ldata.dir = " +pos.getY() + " ldata.enter_effect_index = 0 ldata.compact_map_index = 0 ldata.wall_index = 0 ldata.map_index = 156 ldata.is_safe_zone = 0 ldata.is_task_walk = 0 ldata.floor_index = 0 ldata.map_name = [[" + gameMap.getName() + "]] ldata.map_show_name='" + gameMap.getName() + "' MapMgr:MSG_ENTER_ROOM(ldata, true)";
        resexelua.setMsg(map_s);

        //MapMgr:MSG_ENTER_ROOM(self.for2018HJHD.map, true)  ldata.enter_effect_index = 0 ldata.enter_effect_index = 0 ldata.is_task_walk = 0 ldata.compact_map_index = 0 ldata.floor_index =0 CharMgr:setVisible(false)
        //resexelua.setMsg("local ldata = {} ldata.map_id = 1000 ldata.x = 86 ldata.y = 85 ldata.dir = 5   ldata.wall_index = 1 ldata.map_index = 156     ldata.is_task_walk=false  ldata.map_name = [[天墉城]] MapMgr:MSG_ENTER_ROOM(ldata, true)");
        /* respEnterMap.setDir(pos.getDir());
        respEnterMap.setPosX((short) StanUtils.calcX(pos.getX()));
        respEnterMap.setPosY((short) StanUtils.calcY(pos.getX(), pos.getY()));
        respEnterMap.setMapId(StanUtils.calcMapId(pos.getX(), pos.getY(), pos.getMapId()));
        logger.warn("坐标={}=={}=={}",pos.getX(), pos.getY(), pos.getMapId());
        respEnterMap.setMapName(gameMap.getName());
        respEnterMap.setMap_index(156);
        respEnterMap.setWall_index((byte) 1);
        respEnterMap.setSafe_zone(gameMap.isSafe_zone());*/

        MessagePusher.pushMessage(role, resexelua);
       // MessagePusher.pushMessage(role, respEnterMap);
    }


    /**
     * send 地图传送点信息
     */
    private void sendGameMapTransmission(Role role, int mapId) {
        List<MapTransmission> list = getTrasferInfo(mapId);
        RespMapTransmission respMapTransmission = new RespMapTransmission();
        respMapTransmission.setList(list);
        MessagePusher.pushMessage(role, respMapTransmission);
    }


    /**
     * 广播NPC信息
     */
    public void broadcastNpc(Role role, int mapId) {
        List<NPC> list = getNpcList(new GroupMapParam(role), mapId);
        // 内存中的生成的npc
//        Set<Integer> npcSet = role.getTempCache(Const.npcIdSet, null);
//        if (npcSet != null) {
//            for (Integer id : npcSet) {//给发送NPC消失包
//                RespDisappear respDisappear = new RespDisappear();
//                respDisappear.setId(id);
//                respDisappear.setType((short) Const.NPC);
//                MessagePusher.pushMessage(role, respDisappear);
//            }
//        }
//        npcSet = new HashSet<>();

        for (NPC npc : list) {
            if (!npc.isShow()) {
                continue;
            }
            if (!npc.isMatchPolar((byte) role.getPolar())) {
                continue;
            }
            RespAppear respAppear = new RespAppear();
            respAppear.setRoleId(npc.getId());
            respAppear.setStatus(npc.getIcon());
            respAppear.setPosX(npc.getX());
            respAppear.setPosY(npc.getY());
            respAppear.setType((short) 4);
            respAppear.setDir(npc.getFangxiang());
            respAppear.setRoleName(npc.getName());
            respAppear.setTitle(npc.getTitle());
            respAppear.setOrg_icon(npc.getIcon());
            respAppear.setIcon(npc.getIcon());
            respAppear.setPortrait(npc.getIcon());
            respAppear.setWeaponId(npc.getWuqiId());
            respAppear.setSuit_icon(npc.getTaozhuangId());
            respAppear.setSuit_light_effect(npc.getFaguangId());
            SpringUtils.getMirrorService().changeRespAppear(npc, respAppear);
            AppearanceHandler appearanceHandler = NpcDataPool.appearanceHandlers.get(npc.getId());
            if (appearanceHandler != null) {
                appearanceHandler.changeRespAppear(role, npc, respAppear);
            }
            MessagePusher.pushMessage(role, respAppear);

            RespTitle respTitle = new RespTitle();
            respTitle.setRoleId(npc.getId());
            MessagePusher.pushMessage(role, respTitle);
//            npcSet.add(npc.getId());
        }

//        role.pushTempCache(Const.npcIdSet, npcSet);
    }


    public String getMenPaiName(short menPaiId) {
        String menPaiName;
        if (menPaiId == 1) {
            menPaiName = "五龙山云霄洞";
        } else if (menPaiId == 2) {
            menPaiName = "终南山玉柱洞";
        } else if (menPaiId == 3) {
            menPaiName = "凤凰山斗阙宫";
        } else if (menPaiId == 4) {
            menPaiName = "乾元山金光洞";
        } else if (menPaiId == 5) {
            menPaiName = "骷髅山白骨洞";
        } else {
            menPaiName = "无门无派";
        }

        return menPaiName;
    }

    public short heroIcon(byte sex, short menpai) {
        short icon = 6001;
        if (sex == 1) {//男角色
            if (menpai == 1) {
                icon = 6001;
            } else if (menpai == 2) {
                icon = 7002;
            } else if (menpai == 3) {
                icon = 7003;
            } else if (menpai == 4) {
                icon = 6004;
            } else if (menpai == 5) {
                icon = 6005;
            }
        } else if (sex == 2) {//女角色
            if (menpai == 1) {
                icon = 7001;
            } else if (menpai == 2) {
                icon = 6002;
            } else if (menpai == 3) {
                icon = 6003;
            } else if (menpai == 4) {
                icon = 7004;
            } else if (menpai == 5) {
                icon = 7005;
            }
        }
        return icon;
    }

    /***
     * 是否在对应地图中
     * @param role
     * @param mapId
     * @return
     */
    public boolean isInMap(Role role, int mapId) {
        if (role == null) {
            return false;
        }
        return mapId == role.getPos().getMapId();
    }


    /**
     * 角色是否在指定位置
     *
     * @param role
     * @param mapId
     * @param x
     * @param y
     * @param perimeter 有效范围周长
     */
    public boolean isInPosition(Role role, int mapId, short x, short y, int perimeter) {
        if (role.getPos().getMapId() != mapId) {
            return false;
        }

        /**超过有效范围时，则返回false*/
        int roleX = role.getPos().getX();
        int roleY = role.getPos().getY();

        return Math.abs(roleX - x) <= perimeter && Math.abs(roleY - y) <= perimeter;
    }

    public void addGroupMapNpc(GroupMapParam groupMapParam, NPC npc) {
        int mapId = npc.getMapId();
        Function<Role, Serializable> mapKeyGenerater = MapDataPool.MAP_KEY_GENERATERS.get(mapId);
        if (mapKeyGenerater != null) {
            Serializable key = groupMapParam.getRole() != null ? mapKeyGenerater.apply(groupMapParam.getRole())
                    : groupMapParam.getGroupKey();

            Map<Serializable, Set<Integer>> map = DataCache.GROUP_MAP_NPCIDS
                    .computeIfAbsent(mapId, k -> new ConcurrentHashMap<>());
            Set<Integer> set = map.computeIfAbsent(key, k -> new ConcurrentHashSet<>());
            set.add(npc.getId());
            DataCache.GROUP_NPC.put(npc.getId(), npc);
        }
    }

    public void removeGroupMapNpc(GroupMapParam groupMapParam, NPC npc) {
        int mapId = npc.getMapId();
        Function<Role, Serializable> mapKeyGenerater = MapDataPool.MAP_KEY_GENERATERS.get(mapId);
        if (mapKeyGenerater != null) {
            Serializable key = groupMapParam.getRole() != null ? mapKeyGenerater.apply(groupMapParam.getRole())
                    : groupMapParam.getGroupKey();
            Map<Serializable, Set<Integer>> map = DataCache.GROUP_MAP_NPCIDS.get(mapId);
            if (map != null && key != null) {
                Set<Integer> set = map.get(key);
                if (set != null) {
                    set.remove(npc.getId());
                }
            }

            DataCache.GROUP_NPC.remove(npc);
        }
    }


    public void movePosition(Role role, int x, int y, int dir, int mapId) {
        if (role == null)
            return;
        if (SpringUtils.getFightService().isInFight(role))
            return;
        long now = System.currentTimeMillis();
        if (now - role.getPrevMoveTime() < 1000L)
            return;
        role.setPrevMoveTime(now);
        SpringUtils.getRoleService().recordPositionJH(role, x, y, dir, mapId);
        EventDispatcher.getInstance().fireEvent((BaseGameEvent)new MoveEvent(EventType.MOVE, role));
    }

    public void leaveMap(Role role, int mapId) {
        int oldMapId = mapId;
        EventDispatcher.getInstance().fireEvent((BaseGameEvent)new LeaveMapEvent(EventType.LEAVE_MAP, role, oldMapId));
    }



    public void changeMapWithDir(Role role, int mapId, int x, int y, int dir) {
        if (role == null)
            return;
        if (this.serverService.getServer().getId() == 10000 &&
                mapId != 38004 && mapId != 38000) {
            MessagePusher.pushMessage(role, (Message)new RespNotifyMiscEx("跨服试道中，不能切换地图。"));
            return;
        }
        GameMap gameMap = getMap(mapId);
        if (gameMap == null)
            return;
        if (!checkChangeMap(role))
            return;
        int oldMapId = role.getPos().getMapId();
        EventDispatcher.getInstance().fireEvent((BaseGameEvent)new LeaveMapEvent(EventType.LEAVE_MAP, role, oldMapId));
        role.setPos(x, y, dir, mapId);
        EventDispatcher.getInstance().fireEvent((BaseGameEvent)new EnterMapEvent(EventType.ENTER_MAP, role,oldMapId));
    }

    /**
     * 判断当前人所属地图
     */
    public int roleInMapByType(Role role) {
        int oldMapId = role.getPos().getMapId();
        if(oldMapId == 60000 || oldMapId == 60001 ||oldMapId == 60002 ||oldMapId == 60003 || oldMapId == 60006 || oldMapId == 60007 || oldMapId == 61001){
            return 2;
        }else{
            return 1;
        }
    }
    public int queryMapIdType(int oldMapId) {
        if(oldMapId == 60000 || oldMapId == 60001 ||oldMapId == 60002 ||oldMapId == 60003 || oldMapId == 60006 || oldMapId == 60007 || oldMapId == 61001 ){
            return 2;
        }else{
            return 1;
        }
    }
    }















